package com.bms.api.util;

import java.util.Date;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.feilong.core.Validator;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

public class JwtHelper {

	private static final Logger log = LoggerFactory.getLogger(JwtHelper.class);

	public static SecretKey generalKey() {
		byte[] encodedKey = Base64.decodeBase64("an1rui2xin3feng4lu5pao6ma7la7song9");
		SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
		return key;
	}

	public static Claims parseJWT(String jsonWebToken) {
		try {
			Claims claims = Jwts.parser().setSigningKey(generalKey()).parseClaimsJws(jsonWebToken).getBody();
			return claims;
		} catch (Exception ex) {
			log.error("解析TOKEN出错：{}" + ex.getMessage());
			return null;
		}
	}

	public static String createJWT(String name, String openId) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		long TTLMILLIS = 24L * 60 * 60 * 1000;
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		// 添加构成JWT的参数
		JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").claim("nickName", name).claim("openId", openId)
				.setIssuer("arxf").signWith(signatureAlgorithm, generalKey());
		// 添加Token过期时间
		if (TTLMILLIS >= 0) {
			long expMillis = nowMillis + TTLMILLIS;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp).setNotBefore(now);
		}
		// 生成JWT
		return builder.compact();
	}

	public static String getOpenId(String jsonWebToken) {
		jsonWebToken = jsonWebToken.substring(7, jsonWebToken.length());
		Claims claims = parseJWT(jsonWebToken);
		if (null != claims) {
			return claims.get("openId").toString();
		}
		return null;
	}
}
